//
//  QYXMoreAuthorVC.m
//  OpenYourEyes
//
//  Created by dllo on 16/6/7.
//  Copyright © 2016年 Google AdWords. All rights reserved.
//

#import "QYXMoreAuthorVC.h"
#import "QYXDailyItemListModel.h"
#import "QYXFindMoreModel.h"
#import "QYXDailyTableViewCell.h"
#import "QYXAuthorSigleVC.h"
#import "UINavigationBar+Background.h"
#import "QYXDailyDetailViewController.h"
#import "AppDelegate.h"

@interface QYXMoreAuthorVC ()<UITableViewDelegate, UITableViewDataSource>
/** UITableView */
@property (nonatomic, strong) UITableView *tableView;

/** allArr */
@property (nonatomic, strong) NSMutableArray *allArr;

/** allSecArr */
@property (nonatomic, strong) NSMutableArray *allSecArr;

/** 头视图 */
@property (nonatomic, strong) UIView *headerView ;

@end

@implementation QYXMoreAuthorVC
{
    NSInteger count;
}
- (void)dealloc
{
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    count = 0;
    self.allArr = [NSMutableArray array];
    self.allSecArr = [NSMutableArray array];
    [self creatTableView];
    [self requireData];
    [self creatRefresh];

    UIImage *image = [[UIImage imageNamed:@"back.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.title = @"优质作者";
}


#pragma mark - back
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - 请求TabaleView

- (void)creatTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 240 *KFitHeight;
    self.tableView.sectionHeaderHeight = 60 *KFitHeight;
    self.tableView.sectionFooterHeight = 0.1;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    [self.tableView registerClass:[QYXDailyTableViewCell class] forCellReuseIdentifier:@"QYXDailyTableViewCell"];

}

#pragma mark - Delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_allArr.count == 0) {
        return nil;
    }
    QYXDailyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QYXDailyTableViewCell" forIndexPath:indexPath];
    QYXFindMoreModel *model = self.allSecArr[indexPath.section];
    NSArray *arr = [[self.allArr objectAtIndex:indexPath.section] valueForKey:model.name];
    QYXDailyItemListModel *model2 = [arr objectAtIndex:indexPath.row];
    cell.model = model2;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    QYXFindMoreModel *model = self.allSecArr[section];
    NSArray *arr = [[self.allArr objectAtIndex:section] valueForKey:model.name];
    return arr.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QYXDailyDetailViewController *detailVC = [QYXDailyDetailViewController new];
    QYXFindMoreModel *model = self.allSecArr[indexPath.section];
    NSArray *arr = [[self.allArr objectAtIndex:indexPath.section] valueForKey:model.name];

    detailVC.listDataSource = arr;
    //    detailVC.modelSection = indexPath.section;
    detailVC.modelRow = indexPath.row;
    
    
    AppDelegate *tempDelegate = [UIApplication sharedApplication].delegate;
    tempDelegate.tabBar.backView.hidden = YES;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.allSecArr.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_allArr.count == 0) {
        return nil;
    }
    QYXFindMoreModel *model = self.allSecArr[section];

    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60 *KFitHeight)];
    _headerView.userInteractionEnabled = YES;
    _headerView.backgroundColor = [UIColor colorWithWhite:1.000 alpha:0.713];
    
    _headerView.tag = 1000 + section;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_headerView addGestureRecognizer:tap];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    [_headerView addSubview:imageView];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.icon]];
    
    [imageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_headerView.left).offset(15);
        make.width.and.height.equalTo(30);
        make.centerY.equalTo(_headerView.centerY);
        
        imageView.layer.cornerRadius = 15;
        imageView.layer.masksToBounds = YES;
        
    }];
    
    UILabel *label = [[UILabel alloc] init];
    [_headerView addSubview:label];
    label.textColor = [UIColor colorWithWhite:0.000 alpha:0.8];
    label.font = [UIFont fontWithName:@"FZLTZCHJW--GB1-0" size:14];
    label.text = model.name;
    
    [label makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView.right).offset(15);
        make.width.equalTo(180 *KFitHeight);
        make.height.equalTo(30);
        make.centerY.equalTo(_headerView.centerY);
    }];
    
    UIImageView *minImage = [[UIImageView alloc] init];
    [_headerView addSubview:minImage];
    [minImage makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(_headerView.trailing).offset(-10);
        make.width.and.height.equalTo(15);
        make.centerY.equalTo(_headerView.centerY);
        minImage.image = [UIImage imageNamed:@"right"];
    }];
    
    
    return _headerView;
}

#pragma mark - 分区点击手势 

- (void)tapAction:(UITapGestureRecognizer *)tap
{
    NSInteger index = tap.view.tag - 1000;
    QYXFindMoreModel *model = self.allSecArr[index];
    QYXAuthorSigleVC *vc = [[QYXAuthorSigleVC alloc] init];
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 上拉 下拉刷新

- (void)creatRefresh
{
     __unsafe_unretained __typeof(self) weakSelf = self;
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requireData];
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        count = 0;
        [weakSelf.allArr removeAllObjects];
        [weakSelf.allSecArr removeAllObjects];
        [weakSelf requireData];
    }];
}

#pragma mark - 请求数据

- (void)requireData
{
    __unsafe_unretained __typeof(self) weakSelf = self;

    [QYXNetTool getNetWithUrl:[NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v3/pgcs?_s=982f2e838ed8f89e2704509ef30b55fb&f=iphone&net=wifi&num=%ld&start=%ld&u=ebe4ca1f9d83e4dc4f915b0495e6e1946ee0eb93&v=2.2.0&vc=721", count + 20 , count] urlBody:nil header:nil response:QYXJSON success:^(id result) {
        
        for (NSDictionary *d in result[@"pgcList"]) {

            NSMutableArray *arr =[NSMutableArray array];
          
            NSString *Str;
            for (NSDictionary *xD in d[@"itemList"]) {
               

                if ([xD[@"type"] isEqualToString:@"pgcInfo"]) {
                  QYXFindMoreModel *model = [[QYXFindMoreModel alloc] init];
                    [model setValuesForKeysWithDictionary:xD[@"data"]];
                    [self.allSecArr addObject:model];
                   Str = model.name;
                }
                else
                {
                    QYXDailyItemListModel *model = [[QYXDailyItemListModel alloc] initWithDic:xD[@"data"]];
                    [arr addObject:model];
                }
            }
            
            NSDictionary *dic = [NSDictionary dictionaryWithObject:arr forKey:Str];

            [self.allArr addObject:dic];
            
        }
//        NSLog(@"%@", _allArr);
        
        
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_header endRefreshing];

        count+= 20;
    });
        
    } failure:^(NSError *error) {
        
    }];
}


@end
